// 初始化游戏元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 15;  // 每个格子像素
let snake = [{x: 7, y: 7}];  // 初始位置
let food = generateFood();
let direction = 'right';
let nextDirection = 'right';
let score = 0;

// 初始化游戏状态
let gameStarted = false;
let difficulty = 5;  // 初始难度（1-10）
let speed = 150;  // 初始游戏速度

// 难度调节
document.getElementById('difficultyRange').addEventListener('input', (e) => {
    difficulty = parseInt(e.target.value);
    document.getElementById('difficultyValue').textContent = difficulty;
    speed = 200 - (difficulty - 1) * 20;  // 难度与速度关系：难度越高，游戏越快
});

// 生成食物（不与蛇身重叠）
function generateFood() {
    let newFood;
    do {
        newFood = {
            x: Math.floor(Math.random() * (canvas.width / gridSize)),
            y: Math.floor(Math.random() * (canvas.height / gridSize))
        };
    } while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    return newFood;
}

// 绘制游戏元素
function draw() {
    // 清空画布
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制蛇身
    snake.forEach((segment, index) => {
        ctx.fillStyle = index === 0 ? '#4CAF50' : '#8BC34A';  // 头部颜色不同
        ctx.fillRect(
            segment.x * gridSize, 
            segment.y * gridSize, 
            gridSize - 2, 
            gridSize - 2
        );
    });
    
    // 绘制食物
    ctx.fillStyle = '#ff5252';
    ctx.beginPath();
    ctx.arc(
        food.x * gridSize + gridSize/2,
        food.y * gridSize + gridSize/2,
        gridSize/2 - 2,
        0,
        Math.PI * 2
    );
    ctx.fill();
}

// 游戏逻辑更新
function update() {
    // 更新方向（防止180度转向）
    direction = nextDirection;
    
    // 计算新蛇头位置
    const head = {...snake[0]};
    switch(direction) {
        case 'up': head.y--; break;
        case 'down': head.y++; break;
        case 'left': head.x--; break;
        case 'right': head.x++; break;
    }
    
    // 碰撞检测
    if (head.x < 0 || head.x >= canvas.width / gridSize || 
        head.y < 0 || head.y >= canvas.height / gridSize ||
        snake.some(segment => segment.x === head.x && segment.y === head.y)) {
        alert(`游戏结束！得分：${score}\n点击确定重新开始`);
        resetGame();
        return;
    }
    
    // 移动蛇身
    snake.unshift(head);
    
    // 吃到食物判断
    if (head.x === food.x && head.y === food.y) {
        let foodScore = 5 + difficulty*2;
        score += foodScore;
        document.getElementById('score').textContent = `得分：${score}`;
        food = generateFood();
    } else {
        snake.pop();
    }
}

// 游戏循环
function gameLoop() {
    if (!gameStarted) return;  // 如果游戏没有开始，跳过循环
    update();
    draw();
    setTimeout(gameLoop, speed);  // 控制游戏速度
}

// 键盘控制
document.addEventListener('keydown', (e) => {
    if (!gameStarted) return;  // 如果游戏没有开始，禁止控制
    switch(e.key) {
        case 'ArrowUp':
            if (direction !== 'down') nextDirection = 'up';
            break;
        case 'ArrowDown':
            if (direction !== 'up') nextDirection = 'down';
            break;
        case 'ArrowLeft':
            if (direction !== 'right') nextDirection = 'left';
            break;
        case 'ArrowRight':
            if (direction !== 'left') nextDirection = 'right';
            break;
    }
});

// 读取或设置用户名
function getUsername() {
    let storedUsername = localStorage.getItem("username");
    if (!storedUsername) {
        document.getElementById("usernameInput").style.display = "block"; // 显示输入框
        document.getElementById("usernameDisplay").style.display = "none"; // 隐藏用户名显示
    } else {
        document.getElementById("usernameDisplay").textContent = storedUsername;
        document.getElementById("usernameInput").style.display = "none"; // 隐藏输入框
    }
    return storedUsername || "玩家";
}

let username = getUsername();  // 初始化用户名
let history = JSON.parse(localStorage.getItem("gameHistory")) || []; // 读取本地历史记录

// 更新用户名
document.getElementById("usernameDisplay").addEventListener("click", () => {
    document.getElementById("usernameInput").value = username;
    document.getElementById("usernameInput").style.display = "block";
    document.getElementById("usernameDisplay").style.display = "none";
});

// 输入框失去焦点后保存用户名
document.getElementById("usernameInput").addEventListener("blur", () => {
    let newUsername = document.getElementById("usernameInput").value.trim();
    if (newUsername) {
        username = newUsername;
        localStorage.setItem("username", username);
        document.getElementById("usernameDisplay").textContent = username;
    }
    document.getElementById("usernameInput").style.display = "none";
    document.getElementById("usernameDisplay").style.display = "inline";
});

// 记录游戏历史
function saveGameHistory() {
    let gameRecord = {
        username: username,
        score: score,
        difficulty: difficulty, // 保存当前难度
        time: new Date().toLocaleString()
    };
    history.push(gameRecord);
    localStorage.setItem("gameHistory", JSON.stringify(history)); // 保存到本地
    updateHistoryList();

    // 发送记录到后端
    fetch('/save', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(gameRecord)
    }).then(response => {
        if (!response.ok) {
            console.error('Failed to save game record');
        }
    }).catch(error => {
        console.error('Error:', error);
    });
}

// 更新历史记录列表
function updateHistoryList() {
    let historyList = document.getElementById("historyList");
    historyList.innerHTML = ""; // 清空列表
    history.forEach(record => {
        let listItem = document.createElement("li");
        listItem.style.borderBottom = "1px solid #ddd";
        listItem.style.padding = "5px 0";
        listItem.innerHTML = `得分: ${record.score} 🎚 难度: ${record.difficulty} 🕒 ${record.time}`;
        historyList.appendChild(listItem);
    });
}

// 排序顺序标志
let isAscending = false;

// 按得分排序
document.getElementById("sortBtn").addEventListener("click", () => {
    history.sort((a, b) => isAscending ? a.score - b.score : b.score - a.score);
    isAscending = !isAscending;  // 切换排序顺序
    updateHistoryList();
});

// 按时间排序
document.getElementById("sortByTimeBtn").addEventListener("click", () => {
    history.sort((a, b) => new Date(b.time) - new Date(a.time));
    updateHistoryList();
});

// 清空历史
document.getElementById("clearHistoryBtn").addEventListener("click", () => {
    if (confirm("确定要清空历史记录吗？")) {
        history = [];
        localStorage.removeItem("gameHistory");
        updateHistoryList();
    }
});

// 更新所有玩家的记录列表
function updateAllPlayersList() {
    let allPlayersList = document.getElementById("allPlayersList");
    allPlayersList.innerHTML = ""; // 清空列表

    // 从后端获取所有玩家的记录
    fetch('/records')
        .then(response => response.json())
        .then(records => {
            // 按得分降序排序
            records.sort((a, b) => b.score - a.score);

            records.forEach(record => {
                let listItem = document.createElement("tr");

                // 格式化时间
                let recordTime = new Date(record.time);
                let now = new Date();
                let displayTime;
                if (recordTime.toDateString() === now.toDateString()) {
                    displayTime = recordTime.toLocaleTimeString();
                } else {
                    displayTime = recordTime.toLocaleDateString();
                }

                listItem.innerHTML = `
                    <td>${record.username}</td>
                    <td>${record.score}</td>
                    <td>${record.difficulty}</td>
                    <td class="time-tooltip">${displayTime}
                        <span class="tooltip-text">${record.time}</span>
                    </td>
                `;
                allPlayersList.appendChild(listItem);
            });
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// 游戏结束时调用
function resetGame() {
    saveGameHistory(); // 记录游戏历史
    snake = [{x: 7, y: 7}];
    direction = 'right';
    nextDirection = 'right';
    score = 0;
    food = generateFood();
    document.getElementById('score').textContent = '得分：0';
    gameStarted = false;
    document.getElementById('startBtn').textContent = "开始游戏";
}

// 启动游戏按钮
document.getElementById('startBtn').addEventListener('click', () => {
    if (!gameStarted) {
        gameStarted = true;
        document.getElementById('startBtn').textContent = "暂停游戏";
        gameLoop();
    } else {
        gameStarted = false;
        document.getElementById('startBtn').textContent = "开始游戏";
    }
});

// 监听难度选择
document.getElementById('difficultyRange').addEventListener('input', (e) => {
    difficulty = e.target.value;
    document.getElementById('difficultyValue').textContent = difficulty;
});

// 初始化历史记录
updateHistoryList();
// 初始化所有玩家的记录列表
updateAllPlayersList();